package org.gruposp2p.cometd;

import com.infusion.util.event.EventBroker;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.server.ServerSession;
import org.codehaus.groovy.grails.commons.ApplicationHolder;
import org.springframework.context.ApplicationContext;
import com.infusion.util.event.EventBroker;
import com.infusion.util.event.EventConsumer;

public class AreaChannelMessageProcessor implements EventConsumer {

    private static Logger logger =
            LoggerFactory.getLogger(AreaChannelMessageProcessor.class);

    KarmaMessageService karmaMessageService;
    CometdMessageService messageService;

    public AreaChannelMessageProcessor (KarmaMessageService karmaMessageService) {
        this.karmaMessageService = karmaMessageService;
        ApplicationContext context = (ApplicationContext)ApplicationHolder.
                getApplication().getMainContext();
        EventBroker eventBroker = (EventBroker) context.getBean("eventBroker");
        eventBroker.subscribe(KarmaMessageEvent.AREA_CHANNEL, this);
        messageService = (CometdMessageService) context.getBean("cometdMessageService");
        logger.debug("Subscribed to Event: " + KarmaMessageEvent.AREA_CHANNEL);
    }

    public void processClientMessage (ServerSession remoteClient, Message message) {
    	logger.debug(" handleGroupMessage - message: " + message);
    	//if (!isClusterInitializated) initCluster();
        //Map<String, Object> input = message.getDataAsMap();
        //String name = (String)input.get("name");
        //for (Map.Entry<String, String> entry : map.entrySet()) {
        //	System.out.println("Key : " + entry.getKey()  + " Value : " + entry.getValue());
        //}
        String name =  message.getJSON();
        Map<String, Object> output = new HashMap<String, Object>();
        output.put("greeting", "hooola, " + name);
        remoteClient.deliver(karmaMessageService.getServerSession(),
                "/service/area/**", output, null);
    }

    public void consume(Object event, EventBroker eventBroker) {
        logger.debug(" - consume - message content: "
                + ((KarmaMessageEvent)event).getMessage().getContent());
    }

}